package com.david.config.security;

import com.david.system.pojo.Entity.AuthorityEntity;
import com.david.system.pojo.Entity.UserEntity;
import com.david.system.mapper.AuthorityMapper;
import com.david.system.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.StringJoiner;

@Service
public class UserLoginDetailServiceImpl implements UserDetailsService {

//    private final UserMapper userMapper;
//    private final AuthorityMapper authorityMapper;
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AuthorityMapper authorityMapper;


    public UserLoginDetailServiceImpl() {
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("-------------UserDetails loadUserByUsername-------------");
        UserEntity userEntity = userMapper.selectUserByUsername(username);
        System.out.println("-------------"+userEntity.toString()+"-----------------");
        List<AuthorityEntity> authorities = authorityMapper.selectAuthorityByUsername(username);
        StringJoiner stringJoiner = new StringJoiner(",","","");
        authorities.forEach(authority -> stringJoiner.add(authority.getAuthorityName()));

        System.out.println("-------------获取权限信息:"+ stringJoiner.toString()+"-----------------");
        User user = new User(userEntity.getUsername(), userEntity.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(stringJoiner.toString()));
        System.out.println(user.toString());

        return new User(userEntity.getUsername(), userEntity.getPassword(), AuthorityUtils.commaSeparatedStringToAuthorityList(stringJoiner.toString()));

    }
}
